package com.xidata.dict.translate.baidu;

import com.alibaba.fastjson.JSON;
import com.baidu.translate.HttpGet;
import com.baidu.translate.MD5;
import com.xidata.dict.model.LookupRequest;
import com.xidata.dict.service.TranslateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class BaiduTranslator implements TranslateService {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    @Resource
    private BaiduConfig config;

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", config.getAppId());

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = config.getAppId() + query + salt + config.getAppSecret(); // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    @Override
    public String translate(LookupRequest request) {

        try {
            Thread.sleep(50);
            Map<String, String> params = buildParams(request.getText(), request.getSourceLanguage(), request.getTargetLanguage());
            String result = HttpGet.get(TRANS_API_HOST, params);
            BaiduTranslateResult translateResult = JSON.parseObject(result, BaiduTranslateResult.class);
            if (translateResult == null || translateResult.getTrans_result() == null || translateResult.getTrans_result().isEmpty())
                return null;
            return translateResult.getTrans_result().get(0).dst;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public String getProviderName() {
        return "百度";
    }
}
